/////////////////////////////////////////////////////////////////////////////////////////////////
//
//  Tencent is pleased to support the open source community by making tgfx available.
//
//  Copyright (C) 2023 THL A29 Limited, a Tencent company. All rights reserved.
//
//  Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
//  in compliance with the License. You may obtain a copy of the License at
//
//      https://opensource.org/licenses/BSD-3-Clause
//
//  unless required by applicable law or agreed to in writing, software distributed under the
//  license is distributed on an "as is" basis, without warranties or conditions of any kind,
//  either express or implied. see the license for the specific language governing permissions
//  and limitations under the license.
//
/////////////////////////////////////////////////////////////////////////////////////////////////

#include "GLBuffer.h"
#include "GLContext.h"
#include "GLUtil.h"
#include "core/utils/UniqueID.h"

namespace tgfx {
static unsigned GetTarget(BufferType bufferType) {
  return bufferType == BufferType::Index ? GL_ELEMENT_ARRAY_BUFFER : GL_ARRAY_BUFFER;
}

std::shared_ptr<GpuBuffer> GpuBuffer::Make(Context* context, BufferType bufferType,
                                           const void* buffer, size_t size) {
  // Clear the GL errors generated by the previous operations.
  ClearGLError(context);
  auto gl = GLFunctions::Get(context);
  unsigned bufferID = 0;
  gl->genBuffers(1, &bufferID);
  if (bufferID == 0) {
    return nullptr;
  }
  auto glBuffer = Resource::AddToCache(context, new GLBuffer(bufferType, size, bufferID));
  if (size == 0) {
    return glBuffer;
  }
  auto target = GetTarget(bufferType);
  gl->bindBuffer(target, glBuffer->_bufferID);
  gl->bufferData(target, static_cast<GLsizeiptr>(size), buffer, GL_STATIC_DRAW);
  gl->bindBuffer(target, 0);
  if (!CheckGLError(context)) {
    return nullptr;
  }
  return glBuffer;
}

void GLBuffer::onReleaseGPU() {
  if (_bufferID > 0) {
    auto gl = GLFunctions::Get(context);
    gl->deleteBuffers(1, &_bufferID);
    _bufferID = 0;
  }
}
}  // namespace tgfx
